package com.gitee.zzh.sqllineage.transform;

import com.gitee.zzh.sqllineage.util.SqlStringUtils;

import java.util.List;
import java.util.Set;

public class TransformText extends SqlStringUtils {
    public static String getTransformedText(String text) {
        if(!text.contains("(SELECT ")) {
            return text;
        }
        Set<String> tempTableList = getTempTableList(text);
        if (tempTableList.isEmpty()) {
            return text;
        }
        text = text.replace(" EXISTS(SELECT ", " EXISTS (SELECT ")
                .replace("IN(SELECT ", "IN (SELECT ")
                .replace("=(SELECT ", "= (SELECT ");
        text = addBracketSpace(text, "SELECT", "FROM", "JOIN", "AS", "UNION ALL", "WHERE");
        text = replaceSpace(text);
        return transformText(text, tempTableList);
    }

    public static String transformText(String text, Set<String> tableNameTempList) {
        int k = 0;
        int level = 1;
        while (text.contains ("(SELECT ")) {
            Set<String[]> sqlList = getSelectSqlText(text, tableNameTempList);
            if (sqlList.isEmpty()) {
                return text;
            }
            for (String[] sqlTextAll : sqlList) {
                String sqlText = sqlTextAll[1];
                String tableNameTemp = sqlTextAll[0];
                List<String> sonSqlList = bracketSubStr(sqlText, "(SELECT ");
                for (String sonSql : sonSqlList) {
                    if(sonSql == null || !sqlText.contains(sonSql)) {
                        continue;
                    }
                    k++;
                    String tableNameTempl = tableNameTemp + "_MANUAL_S_" + level + "_" + k;
                    if (text.contains(sonSql + " ") || text.contains(sonSql + ";")) {
                        text = text.replace(sonSql, tableNameTempl);
                    } else {
                        String right = text.substring(text.indexOf(sonSql) + sonSql.length());
                        String alias = substringBySymbol(right, " ", ";", "(", ")");
                        alias = substringByLastSymbol(alias, ";", "(", ")");
                        text = text.replace(sonSql + alias, tableNameTempl + " " + alias);
                    }
                    String tSqlText = "DROP TABLE IF EXISTS " + tableNameTempl + ";CREATE TABLE "
                            + tableNameTempl + " AS " + sonSql.substring(1, sonSql.length() - 1) + ";";
                    if(text.trim().endsWith(";")) {
                        text = text + tSqlText;
                    } else {
                        text = text + ";" + tSqlText;
                    }
                }
            }
            tableNameTempList = getTempTableList(text);
        }
        return text;
    }

}
